import type { TypedOptions } from "typed.js";
import type { PropType } from "vue";
import Typed from "typed.js";
import { defineComponent, onBeforeUnmount, onMounted, ref } from "vue";

// 实现打字机效果，利用开源的typed.js实现
// https://juejin.cn/post/7020208396271878152#heading-20
export default defineComponent({
    name: "Typed",
    props: {
        // 这里是Typed.js的配置选项
        options: {
            // 踩坑：这里的类型声明要写成`Object as PropType<TypedOptions>`
            // 不能直接写成TypedOptions，这样会找不到类型声明
            type: Object as PropType<TypedOptions>,
            required: true,
        },
        // 这里是打字机效果的容器id
        // 注意：这个id必须是唯一的，不能和其他元素重复
        id: {
            type: String,
            required: true,
        },
    },
    setup(props) {
        const typedInstance = ref<Typed | null>(null);

        onMounted(() => {
            typedInstance.value = new Typed(`#${props.id}`, props.options);
        });

        onBeforeUnmount(() => {
            // 销毁 Typed 实例，避免内存泄漏
            typedInstance.value?.destroy();
        });

        return () => <div id={props.id}></div>;
    },
});
